package com.whccb.apps.office.document.event.receive;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListenerInterface;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.HistoryTaskInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.TaskInstance;
import com.actionsoft.bpms.commons.pagination.SQLPagination;
import com.actionsoft.bpms.org.cache.DepartmentCache;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.org.model.DepartmentModel;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.util.ConsolePrinter;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.exception.BPMNError;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;

public class ChairmanOpinionToSubProcessAndNoticeAfterFormSaveEvent
        extends ExecuteListener implements ExecuteListenerInterface {

    public String getDescription() {
        return "收文流程中，文书岗根据董事长批示意见决定增加或删除会签分支，"
                + "并代录入董事长批示后，将相关批示信息反写回对应子流程中，给相关会签人员发出通知提醒。";
    }

    public String getProvider() {
        return "ActionSoft";
    }

    public String getVersion() {
        return "AWS 6.0";
    }

    @Override
    public void execute(ProcessExecutionContext pec) throws Exception {
        BO swBo = SDK.getBOAPI().getByProcess("BO_WHBK_OD_RECEIVE",
                pec.getProcessInstance().getId());
        String receive = "";
        if (swBo != null) {
            List<ProcessInstance> subProcessList = SDK.getProcessAPI().query()
                    .parentProcessInstId(pec.getProcessInstance().getId())
                    .list();
            // 给行领导批示节点办理者发送通知
            String notifyuserid = "";
            StringBuffer notifycontent = new StringBuffer();
            notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
                    .append(",文号为：").append(swBo.getString("FILENUM"))
                    .append("的收文流程，董事长有最新的批示，请及时查阅！");
            // 查询任务代办
            List<TaskInstance> tasklist = SDK.getTaskQueryAPI()
                    .processInstId(pec.getProcessInstance().getId())
                    .activityDefId("obj_c7496d875a3000011bfb7a507d201a12")
                    .orderByBeginTime().desc().list();

            if (tasklist != null && !tasklist.isEmpty()
                    && tasklist.size() > 0) {
                for (TaskInstance ti : tasklist) {
                    if (StringUtils.isBlank(notifyuserid)) {
                        notifyuserid = ti.getTarget();
                    } else {
                        if (!notifyuserid.contains(ti.getTarget())) {// 判断是否发送过消息
                            notifyuserid += " " + ti.getTarget();
                        } else {
                            continue;
                        }
                    }
                    SDK.getTaskAPI().createUserNotifyTaskInstance(
                            pec.getProcessInstance().getId(), ti.getId(),
                            "admin", ti.getTarget(), notifycontent.toString());
                }
            }
            // 查询历史任务实例
            List<HistoryTaskInstance> tasklist2 = SDK.getHistoryTaskQueryAPI()
                    .processInstId(pec.getProcessInstance().getId())
                    .activityDefId("obj_c7496d875a3000011bfb7a507d201a12")
                    .orderByBeginTime().desc().list();
            if (tasklist2 != null && !tasklist2.isEmpty()
                    && tasklist2.size() > 0) {
                for (TaskInstance ti : tasklist2) {
                    if (StringUtils.isBlank(notifyuserid)) {
                        notifyuserid = ti.getTarget();
                    } else {
                        if (!notifyuserid.contains(ti.getTarget())) {
                            notifyuserid += " " + ti.getTarget();
                        } else {
                            continue;
                        }
                    }
                    SDK.getTaskAPI().createUserNotifyTaskInstance(
                            pec.getProcessInstance().getId(), ti.getId(),
                            "admin", ti.getTarget(), notifycontent.toString());
                }
            }

            String chairmanOption = swBo.getString("CHAIRMAN");
            String doUseridStr = swBo.getString("DOUSERID");
            if (StringUtils.isNotEmpty(doUseridStr)) {
                String[] doUserids = doUseridStr.split(",");
                if (doUserids != null && doUserids.length > 0) {
                    // 查询出该收文流程对应的子流程
                    for (String doUserid : doUserids) {
                        if (StringUtils.isNotEmpty(doUserid)) {
                            // 检查所有子流程中是否有该启动者，没有表示是新增的，则需要创建
                            boolean isCreateSub = true;
                            if (subProcessList != null
                                    && !subProcessList.isEmpty()
                                    && subProcessList.size() > 0) {
                                for (ProcessInstance subProcess : subProcessList) {
                                    if (subProcess != null) {
                                        if (doUserid.equals(
                                                subProcess.getCreateUser())) {
                                            isCreateSub = false;
                                            BO swDoBo = SDK.getBOAPI()
                                                    .getByProcess(
                                                            "BO_WHBK_OD_RECEIVE_DO",
                                                            subProcess.getId());
                                            if (swDoBo != null) {
                                                swDoBo.set("CHAIRMAN",
                                                        chairmanOption);
                                                SDK.getBOAPI().updateByBindId(
                                                        "BO_WHBK_OD_RECEIVE_DO",
                                                        swDoBo.getBindId(),
                                                        "CHAIRMAN",
                                                        chairmanOption);
                                                // 再更新签批附件
                                                SDK.getBOAPI().removeFiles(
                                                        swDoBo.getId(),
                                                        "CHAIRMANPDF");
                                                SDK.getBOAPI().copyFileTo(
                                                        swBo.getId(),
                                                        "CHAIRMANPDF",
                                                        swDoBo.getId(),
                                                        "BO_WHBK_OD_RECEIVE_DO",
                                                        "CHAIRMANPDF",
                                                        swDoBo.getBindId(),
                                                        null);
                                                String isSendNotice = swBo
                                                        .getString(
                                                                "ISONLYDOUSERNAME");
                                                if ("0".equals(isSendNotice)) {

                                                    sendNotify(
                                                            subProcess.getId(),
                                                            swDoBo);
                                                }

                                            }
                                            subProcessList.remove(subProcess);
                                            break;
                                        }
                                    }
                                }
                            }
                            // 循环完毕
                            if (isCreateSub) {// 所有子流程的启动者都不是该帐号，说明是新增的子流程
                                String thisReceive = addsub(
                                        pec.getUserContext().getSessionId(),
                                        swBo, pec.getProcessInstance().getId(),
                                        ODConstant.OD_SW_PARENT_SUBPROCESS_TASKDEFID,
                                        doUserid);
                                if (StringUtils.isNotEmpty(thisReceive)) {
                                    receive = receive + "&" + thisReceive;
                                }
                            }
                        }
                    }
                }
            }

            if (subProcessList != null && !subProcessList.isEmpty()
                    && subProcessList.size() > 0) {// 剩下的是需要删除的分支
                for (ProcessInstance subProcess : subProcessList) {
                    if (subProcess != null) {
                        SDK.getProcessAPI().delete(subProcess,
                                pec.getUserContext());
                    }

                }

            }
        }

        if (StringUtils.isNotEmpty(receive)) {
            throw new BPMNError("wsyh-01", receive);
        }
    }

    private void sendNotify(String subBinid, BO swBo) {
        if (StringUtils.isNotEmpty(subBinid) && swBo != null) {
            // 得到子流程的第一节点办理人，即为任务提醒人
            String notifyUserid = "";
            String subTaskId = "";
            List<TaskInstance> taskList = SDK.getTaskAPI().query()
                    .activityDefId(ODConstant.SWBL_TASK_DEFID)
                    .processInstId(subBinid).list();
            if (taskList != null && !taskList.isEmpty()
                    && taskList.size() > 0) {
                notifyUserid = taskList.get(0).getTarget();
                subTaskId = taskList.get(0).getId();
            } else {
                List<HistoryTaskInstance> taskHisList = SDK.getTaskAPI()
                        .queryHistory()
                        .activityDefId(ODConstant.SWBL_TASK_DEFID)
                        .processInstId(subBinid).list();
                if (taskHisList != null && !taskHisList.isEmpty()
                        && taskHisList.size() > 0) {
                    notifyUserid = taskHisList.get(0).getTarget();
                    subTaskId = taskHisList.get(0).getId();
                }
            }

            // 发送通知
            // JSONObject json = new JSONObject();
            StringBuffer notifycontent = new StringBuffer();
            notifycontent.append("来文机构:").append(swBo.getString("RECEIVEORG"))
                    .append(",文号为：").append(swBo.getString("FILENUM"))
                    .append("的收文流程，董事长有最新的批示，请及时查阅！");
            // json.put("notifycontent", notifycontent.toString());
            // json.put("bindid", subBinid);
            // json.put("taskid", subTaskId);
            // json.put("title", notifycontent.toString());
            // json.put("processInstId", subBinid);
            // json.put("taskInstId", subTaskId);
            // Map<String, Object> params = new HashMap<String, Object>();
            // params.put("sender", "admin");
            // params.put("targetIds", notifyUserid);
            // params.put("content", json.toString());
            // params.put("systemName", ODConstant.NOTIFY_SYSNAME);
            // params.put("systemName", "我的工作台");

            ConsolePrinter.info("发送消息内容---" + notifycontent.toString());
            ConsolePrinter.info("发送消息---" + notifyUserid);
            SDK.getTaskAPI().createUserNotifyTaskInstance(subBinid, subTaskId,
                    "admin", notifyUserid, notifycontent.toString());
            // ODAppUtil.sendOfficeDocumentNotification(params);
        }
    }

    /**
     * 收文流程在主流程中主动增加子流程分支
     * 
     */
    public String addsub(String sid, BO parentBo, String parentProcessinstid,
            String parentTaskDefid, String useridstr) {
        String backMessage = "";
        String queryCallActivityTaskInstId = "select ID from WFC_TASK where PROCESSINSTID = :PROCESSINSTID and ACTIVITYDEFID = :ACTIVITYDEFID ";
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("PROCESSINSTID", parentProcessinstid);
        params.put("ACTIVITYDEFID", parentTaskDefid);
        String callActivityTaskInstId = DBSql
                .getString(
                        SQLPagination.getPaginitionSQL(
                                queryCallActivityTaskInstId, 0, 1),
                        "ID", params);

        if (StringUtils.isNotEmpty(callActivityTaskInstId)) {
            if (StringUtils.isNotEmpty(useridstr)) {
                String[] userids = useridstr.split(",");
                for (String userid : userids) {
                    if (StringUtils.isNotEmpty(userid)
                            && UserCache.getModel(userid) != null) {

                        UserModel user = UserCache.getModel(userid);
                        DepartmentModel dept = DepartmentCache
                                .getModel(user.getDepartmentId());
                        ProcessInstance subProcessInst = SDK.getProcessAPI()
                                .createSubProcessInstance(userid, "追加收文办理流程",
                                        callActivityTaskInstId, null);
                        // 同步BO数据
                        SDK.getBOAPI().query("BO_WHBK_OD_RECEIVE", true)
                                .addQuery("BINDID =", parentProcessinstid)
                                .copyTo("BO_WHBK_OD_RECEIVE_DO",
                                        subProcessInst.getId())
                                .exec();

                        SDK.getProcessAPI().start(subProcessInst);
                        BO subBo = SDK.getBOAPI().getByProcess(
                                "BO_WHBK_OD_RECEIVE_DO",
                                subProcessInst.getId());
                        // 将填加的账户同步加至主流程的会签经理
                        if (parentBo != null) {
                            // 同步处理签批信息
                            // 构建父流程的签批DC，将其复制到子流程相应位置。
                            String parentDCGroupValue = parentBo.getBindId();
                            String parentDCFileValue = parentBo.getId();
                            String subDCGroupValue = subBo.getBindId();
                            String subDCFileValue = subBo.getId();

                            String leaderStr = parentBo.getString("LEADERSIGN");

                            // 手写签批改了存储方式，此处需要修改

                        }
                        // backMessage = "添加成功，请通过跟踪图并刷新页面查看";
                    } else {
                        backMessage = useridstr + "帐号不合法";
                    }
                }
            } else {
                backMessage = useridstr + "帐号为空";
            }
        } else {
            backMessage = "当前所有收文办理子流程已经结束，不允许增加分支，" + useridstr + "的任务增加失败。";
        }
        return backMessage;
    }

}
